package com.example.module_home.testmvi2

import androidx.lifecycle.viewModelScope
import com.example.lib_mvicore.viewmodel.BaseViewModel
import com.example.module_home.model.service.VideoTypeService

import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch

/**
 * @author yaotianxue
 * @description
 * @date 2024/10/25
 */
class VideTypeViewModel:BaseViewModel<VideoTypeIntent>() {
    private val service by lazy{VideoTypeService()}
    //状态：state
    private val _getSimpleTypeState = MutableStateFlow<VideoTypeState>(VideoTypeState.Loading)
    val getSimpleTypeState = _getSimpleTypeState.asStateFlow()

    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when (it){
                    is VideoTypeIntent.GetMutilType -> getMutilTypeData()
                    is VideoTypeIntent.GetMutilTypeByPid -> getMutilTypeDataByPid(it.pid)
                    is  VideoTypeIntent.GetSimpleType -> getSimpleTypeData()
                }
            }
        }
    }

    /**
     * 根据请求到数据结果更新state
     */
    private  fun getSimpleTypeData() {
        viewModelScope.launch {
            flow {
                emit(service.getSimpleType())
            }.catch { e->
                _getSimpleTypeState.value = VideoTypeState.Error(e.message.toString())
            }.filter {
                it != null
            }.collect{
                if(it.code == 0){
                    if(it.data.isEmpty()){
                        _getSimpleTypeState.value = VideoTypeState.Empty
                    }else{
                        _getSimpleTypeState.value = VideoTypeState.GetSimpleTypeSuccess(it.data)
                    }
                }else{
                    _getSimpleTypeState.value = VideoTypeState.Error(it.msg)
                }
            }
        }

    }
    private  fun getMutilTypeData() {

    }
    private  fun getMutilTypeDataByPid(pid:Int) {

    }
}